import { memo, forwardRef, useImperativeHandle, useState, useEffect } from 'react'
import { message, Select } from 'antd'
import bus from '../../utils/eventBus'

const LdPrinters = forwardRef((props: any, ref: any) => {
    const { value = '', getSelect } = props
    const [selfValue, setSelfValue] = useState<string>('')
    const [options, setOptions] = useState<any[]>([])
    const onChange = (value: string) => {
        getSelect && getSelect(value)
    }
    const load = () => {
        window.chromePro.getPrinterInfo();
    }
    const getPrinterInfoFinished = (res: any) => {
        if (res.code === 200) {
            const data = [...res.data]
            data.map(item => {
                item.label = item.printerName
                item.value = item.printerName
            })
            setOptions([...data])
            console.log(res.data, "打印机数据！！");
        }
    }
    const getDefaultPrinterFinished = (data: any) => {
        console.log('默认打印机', data)
        if (data.code === 200) {
            const defaultPrint = data.defaultPrinter ? data.defaultPrinter : options.length ? options[0].printerName : ''
            setSelfValue(defaultPrint)
            getSelect && getSelect(defaultPrint)
        } else {
            message.error(data.msg);
        }
    }
    useEffect(() => {
        setSelfValue(value)
    }, [value])
    useEffect(() => {
        window.chromePro.getPrinterInfo();
        window.chromePro.getDefaultPrinter();
        bus.addListener("getPrinterInfoFinished", getPrinterInfoFinished);
        bus.addListener('getDefaultPrinterFinished', getDefaultPrinterFinished)
        if (window.chromePro) {
        } else {
            bus.addListener("load", load);
        }
    }, [])
    useEffect(() => {
        return () => {
            bus.removeListener('getDefaultPrinterFinished', getDefaultPrinterFinished)
            bus.removeListener("getPrinterInfoFinished", getPrinterInfoFinished);
            bus.removeListener("load", load);
        }
    },[])
    useImperativeHandle(ref, () => ({
        options
    }))
    return (
        <>
            <Select style={{ width: '100%' }} value={selfValue} options={options} onChange={onChange} placeholder="请选择打印机"></Select>
        </>
    )
})

export default memo(LdPrinters)